// pages/search/search.vue
<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-container">
        <uni-icons type="search" size="18" color="#7f8c8d"></uni-icons>
        <input 
          class="search-input" 
          placeholder="输入关键词搜索..." 
          v-model="searchKeyword"
          @input="handleSearch"
          focus
        />
        <view v-if="searchKeyword" class="clear-btn" @click="clearSearch">
          <uni-icons type="clear" size="16" color="#7f8c8d"></uni-icons>
        </view>
      </view>
      <view class="cancel-btn" @click="goBack">取消</view>
    </view>

    <!-- 搜索结果 -->
    <scroll-view scroll-y class="search-results" v-if="searchResults.length > 0">
      <view class="results-count">找到 {{ searchResults.length }} 个结果</view>
      <view 
        v-for="(item, index) in searchResults" 
        :key="getResultKey(item)"
        class="result-item"
        :data-path="item.path"
        :data-title="item.title"
        :data-id="item.id"
        :data-index="index"
        @click="handleItemClick"
      >
        <uni-icons 
          :type="item.isFolder ? 'folder-filled' : 'file-filled'" 
          size="18" 
          :color="item.isFolder ? '#f39c12' : '#95a5a6'"
        ></uni-icons>
        <view class="result-content">
          <text class="result-title" user-select>{{ getItemTitle(item) }}</text>
          <text class="result-path" user-select>{{ getItemPath(item) }}</text>
          <text v-if="item.description" class="result-desc" user-select>{{ item.description }}</text>
        </view>
        <uni-icons type="arrowright" size="14" color="#bdc3c7"></uni-icons>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else-if="searchKeyword && !isSearching" class="empty-state">
      <text class="empty-text" user-select>未找到相关结果</text>
      <text class="empty-tip" user-select>尝试使用其他关键词搜索</text>
    </view>

    <!-- 搜索提示 -->
    <view v-else class="search-tips">
      <view class="tips-header" user-select>搜索提示</view>
      <view class="tip-item">
        <uni-icons type="info" size="14" color="#3498db"></uni-icons>
        <text class="tip-text" user-select>支持标题、路径、描述的关键词搜索</text>
      </view>
      <view class="tip-item">
        <uni-icons type="info" size="14" color="#3498db"></uni-icons>
        <text class="tip-text" user-select>文件夹和文档都会在结果中显示</text>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="isSearching" class="search-loading">
      <view class="loading-spinner"></view>
      <text class="loading-text" user-select>搜索中...</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'SearchPage',
  data() {
    return {
      searchKeyword: '',
      searchResults: [],
      isSearching: false,
      treeData: [],
      listData: [],
      searchTimer: null,
      hasSearched: false
    };
  },
  onLoad() {
    console.log('搜索页面加载');
    this.getGlobalData();
  },
  onUnload() {
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
      this.searchTimer = null;
    }
  },
  methods: {
    getResultKey(item) {
      if (!item) return `result-${Date.now()}-${Math.random()}`;
      return item.id ? `result-${item.id}` : `result-${item.path}-${Date.now()}`;
    },
    
    getItemTitle(item) {
      if (!item) return '未知标题';
      return item.title || '无标题';
    },
    
    getItemPath(item) {
      if (!item) return '未知路径';
      return item.path || '';
    },

    getGlobalData() {
      try {
        const treeData = uni.getStorageSync('wiki_tree_data');
        const listData = uni.getStorageSync('wiki_list_data');
        
        if (treeData && listData) {
          this.treeData = treeData;
          this.listData = listData;
          console.log('搜索数据加载成功，树数据:', treeData.length, '列表数据:', listData.length);
        } else {
          console.warn('未找到缓存数据，搜索功能可能受限');
          this.tryGetDataFromHomePage();
        }
      } catch (e) {
        console.error('获取全局数据失败:', e);
      }
    },

    tryGetDataFromHomePage() {
      try {
        const pages = getCurrentPages();
        if (pages.length > 0) {
          const homePage = pages[0];
          if (homePage && homePage.$vm) {
            this.treeData = homePage.$vm.structuredTreeData || [];
            this.listData = homePage.$vm.listData || [];
            console.log('从首页获取数据成功');
          }
        }
      } catch (error) {
        console.error('从首页获取数据失败:', error);
      }
    },

    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.searchResults = [];
        this.hasSearched = false;
        return;
      }

      this.isSearching = true;
      this.hasSearched = true;
      
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }
      
      this.searchTimer = setTimeout(() => {
        this.performSearch();
      }, 300);
    },

    performSearch() {
      console.log('开始搜索，关键词:', this.searchKeyword);
      console.log('可用数据 - 树数据:', this.treeData.length, '列表数据:', this.listData.length);
      
      const keyword = this.searchKeyword.toLowerCase().trim();
      const results = [];

      this.searchResults = [];

      // 搜索列表数据（文档）
      if (this.listData && Array.isArray(this.listData)) {
        for (const item of this.listData) {
          if (item && this.matchItem(item, keyword)) {
            if (!results.some(result => result.id === item.id)) {
              results.push({
                ...item,
                isFolder: false
              });
            }
          }
        }
      }

      // 搜索树数据（文件夹）
      if (this.treeData && this.treeData.length > 0) {
        this.searchTreeData(this.treeData, keyword, results);
      }

      const uniqueResults = this.removeDuplicates(results);
      
      console.log('搜索完成，找到结果:', uniqueResults.length);
      uniqueResults.forEach((item, index) => {
        console.log(`结果 ${index + 1}:`, item.title, item.path, item.isFolder ? '(文件夹)' : '(文件)');
      });
      
      this.searchResults = uniqueResults;
      this.isSearching = false;
    },

    searchTreeData(nodes, keyword, results) {
      if (!nodes || !Array.isArray(nodes)) return;
      
      const queue = [...nodes];
      
      while (queue.length > 0) {
        const node = queue.shift();
        if (!node) continue;
        
        if (this.matchItem(node, keyword)) {
          if (!results.some(result => result.id === node.id)) {
            results.push({
              ...node,
              isFolder: true
            });
          }
        }
        
        if (node.children && Array.isArray(node.children)) {
          queue.push(...node.children);
        }
      }
    },

    removeDuplicates(results) {
      const seen = new Set();
      return results.filter(item => {
        if (!item) return false;
        
        const identifier = item.id || item.path;
        if (seen.has(identifier)) {
          return false;
        }
        seen.add(identifier);
        return true;
      });
    },

    matchItem(item, keyword) {
      if (!item || !keyword) return false;
      
      if (!keyword.trim()) return false;
      
      const searchFields = [
        item.title,
        item.path, 
        item.description
      ];
      
      return searchFields.some(field => {
        if (!field) return false;
        return field.toLowerCase().includes(keyword);
      });
    },

    clearSearch() {
      this.searchKeyword = '';
      this.searchResults = [];
      this.hasSearched = false;
      this.isSearching = false;
      
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
        this.searchTimer = null;
      }
    },

    goBack() {
      uni.navigateBack();
    },

    // 修复点击事件处理 - 从事件对象获取数据
    handleItemClick(event) {
      console.log('点击事件:', event);
      
      // 从 data- 属性获取数据
      const dataset = event.currentTarget.dataset;
      const path = dataset.path;
      const title = dataset.title;
      const id = dataset.id;
      const index = dataset.index;
      
      console.log('点击了结果:', index, '路径:', path, '标题:', title, 'ID:', id);
      
      if (!path) {
        console.error('跳转失败：路径为空', dataset);
        uni.showToast({
          title: '跳转失败，数据异常',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      
      // 方案1：直接跳转
      this.directNavigate(path, title);
    },

    // 直接跳转方案
    directNavigate(path, title) {
      const url = `/pages/index/index?path=${encodeURIComponent(path)}&title=${encodeURIComponent(title || '未知标题')}&from=search`;
      
      console.log('跳转URL:', url);
      
      uni.navigateTo({
        url: url,
        success: () => {
          console.log('navigateTo 跳转成功');
        },
        fail: (err) => {
          console.error('navigateTo 跳转失败:', err);
          // 方案2：使用重定向
          this.useRedirectTo(path, title);
        }
      });
    },

    // 重定向方案
    useRedirectTo(path, title) {
      const url = `/pages/index/index?path=${encodeURIComponent(path)}&title=${encodeURIComponent(title || '未知标题')}&from=search_redirect`;
      
      uni.redirectTo({
        url: url,
        success: () => {
          console.log('redirectTo 跳转成功');
        },
        fail: (err) => {
          console.error('redirectTo 跳转失败:', err);
          // 方案3：使用存储方案
          this.useStorageFallback(path, title);
        }
      });
    },

    // 存储备用方案
    useStorageFallback(path, title) {
      try {
        // 使用最简单的存储方式
        uni.setStorageSync('search_jump_path', path);
        uni.setStorageSync('search_jump_title', title || '未知标题');
        
        console.log('存储跳转信息成功:', path);
        
        // 返回首页
        uni.navigateBack({
          delta: 1,
          success: () => {
            console.log('返回首页成功');
          },
          fail: (err) => {
            console.error('返回首页失败:', err);
            uni.showToast({
              title: '跳转失败，请手动返回首页',
              icon: 'none',
              duration: 2000
            });
          }
        });
      } catch (e) {
        console.error('存储失败:', e);
        uni.showToast({
          title: '系统错误，请重启应用',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.search-container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  
  .search-input-container {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #f8f9fa;
    border-radius: 20px;
    margin-right: 10px;
    
    .search-input {
      flex: 1;
      margin: 0 8px;
      font-size: 16px;
    }
    
    .clear-btn {
      padding: 4px;
    }
  }
  
  .cancel-btn {
    font-size: 16px;
    color: #3498db;
  }
}

.search-results {
  max-height: calc(100vh - 120px);
  
  .results-count {
    padding: 15px;
    font-size: 14px;
    color: #7f8c8d;
    background-color: #fff;
    border-bottom: 1px solid #eee;
  }
  
  .result-item {
    display: flex;
    align-items: center;
    padding: 15px;
    background-color: #fff;
    border-bottom: 1px solid #f8f9fa;
    
    &:active {
      background-color: #f8f9fa;
    }
    
    .result-content {
      flex: 1;
      margin-left: 12px;
      display: flex;
      flex-direction: column;
      
      .result-title {
        font-size: 16px;
        color: #2c3e50;
        margin-bottom: 4px;
      }
      
      .result-path {
        font-size: 12px;
        color: #95a5a6;
        margin-bottom: 4px;
      }
      
      .result-desc {
        font-size: 13px;
        color: #7f8c8d;
        line-height: 1.4;
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  
  .empty-text {
    font-size: 16px;
    color: #95a5a6;
    margin-bottom: 8px;
  }
  
  .empty-tip {
    font-size: 14px;
    color: #bdc3c7;
  }
}

.search-tips {
  padding: 30px 20px;
  
  .tips-header {
    font-size: 16px;
    color: #2c3e50;
    margin-bottom: 15px;
    text-align: center;
  }
  
  .tip-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    
    .tip-text {
      margin-left: 8px;
      font-size: 14px;
      color: #7f8c8d;
    }
  }
}

.search-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  
  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #f3f3f3;
    border-top: 3px solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
  }
  
  .loading-text {
    font-size: 14px;
    color: #7f8c8d;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>